package praktikumid.w10.p1;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

/**
 * Polygon shape.
 * @author Ago
 *
 */
public class ClosedShape extends Shape {

	/**
	 * Polygon is defined by points, which
	 * are connected with lines when shape is drawn.
	 */
	List<Point> points = new ArrayList<Point>();
	
	/**
	 * Whether the last point is done 
	 * (while we drag, we still want to 
	 * change the location for the last point).
	 */
	boolean lastPointDone = true;
	
	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		if (points.size() == 0) return;
		// connect every point the previous point
		for (int i = 1; i < points.size(); i++) {
			g.drawLine(points.get(i).x, points.get(i).y, 
					points.get(i - 1).x, points.get(i - 1).y);
		}
		if (isFinished) {
			// if shape is finished, connect the first and
			// the last point.
			g.drawLine(points.get(0).x, points.get(0).y, 
					points.get(points.size() - 1).x,
					points.get(points.size() - 1).y
					);
		}
	}

	@Override
	public void drag(MouseEvent e) {
		if (!isFinished) {
			if (points.size() == 0) {
				// when we start drawing,
				// let's add the first point here
				points.add(e.getPoint());
			}
			if (lastPointDone) {
				// if last point is done
				// we need to add a new one
				System.out.println("add point");
				points.add(e.getPoint());
				lastPointDone = false;
			} else {
				// if last point is not done,
				// let's just change the location
				points.get(points.size() - 1).setLocation(e.getPoint());
			}
		}
		
	}

	@Override
	public void click(MouseEvent e) {
		if (e.getButton() == MouseEvent.BUTTON3) {
			// change the color of the shape
			/*
			 * in other packages, this is
			 * achieved differently
			 * (in more proper way).
			 */
			setColor(Color.RED);
		}
		if (!isFinished) {
			if (e.getClickCount() > 1) {
				// double click, let's finish the shape
				isFinished = true;
			} else {
				points.add(e.getPoint());
			}
		}
		
	}

	@Override
	public void release(MouseEvent e) {
		if (!isFinished) {
			if (!lastPointDone) {
				lastPointDone = true;
			}
		}
		
	}

	@Override
	public void move(int dx, int dy) {
		for (Point p : points) {
			// we need to move every point
			p.setLocation(p.x + dx, p.y + dy);
		}
	}

}
